﻿using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;

public class TcpChatRoom : MonoBehaviour
{
    public const string ipAddress = "127.0.0.1";

    public const int port = 7788;

    private Socket clientScoket;

    private Thread receiveThread;

    private byte[] msgData = new byte[1024];

    private string message;//临时保存数据，线层中不可以直接操作UI组件

    public InputField input;

    public Text msgText;

    private void Start()
    {
        msgText.text = "";

        ConnectToServer();

        //接受数据的线程
        receiveThread = new Thread(ReceiveMessage);
        receiveThread.Start();
    }

    private void ConnectToServer()
    {
        clientScoket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
        
        clientScoket.Connect(new IPEndPoint(IPAddress.Parse(ipAddress),port));

        Debug.Log("已连接服务器");
    }

    public void SendBtnOnClick()
    {
        string message = input.text;
        if (string.IsNullOrEmpty(message))
        {
            Debug.LogError("消息不能为空");
            return;
        }
        SendMessageToServer(message);

        input.text = "";
    }

    private void SendMessageToServer(string message)
    {
        byte[] data = Encoding.UTF8.GetBytes(message);
        clientScoket.Send(data);
    }

    private void ReceiveMessage()
    {
        while (true)
        {
            if (clientScoket.Connected==false)
            {
                break;
            }

            int length = clientScoket.Receive(msgData);
            Debug.LogError("receives");
            message = Encoding.UTF8.GetString(msgData,0,length);
        }
    }

    private void Update()
    {
        if (!string.IsNullOrEmpty(message))
        {
            msgText.text += "\n" + message;
            Debug.Log(message);
            message = "";
        }
    }

    private void OnDestroy()
    {
        clientScoket.Shutdown(SocketShutdown.Both);
        clientScoket.Close();
    }
}
